package uit.nfcmenu.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.UnknownHostException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import android.content.Context;
import android.util.Log;

/**
 * @author LanTran from TanNguyen
 */

public class WebserviceHelper {
	final static String tag = WebserviceHelper.class.getSimpleName();

	protected static WebserviceHelper instance;
	protected static DefaultHttpClient client; // = new DefaultHttpClient();

	/**
	 * 
	 */

	public WebserviceHelper() {
		
	}

	/*
	 * service one client one time
	 */
	public static WebserviceHelper getInstance() {
		if (instance == null) {
			instance = new WebserviceHelper();
			client = new DefaultHttpClient();
			HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
		}
		return instance;
	}

	public static void destroyInstance() {
		if (instance != null) {
			instance = null;
			client = null;
		}
	}

	/** TODO
	 * Method used to get a response from web-services 
	 * @param url: the url for ws action
	 * @param body: 
	 * @return
	 */
//	public static HttpResponse callWS(String url, String body) {
//		HttpResponse response = null;
//		try {
//			HttpPost post = new HttpPost(url);
//			StringEntity entity = new StringEntity(body, "UTF-8");
//			entity.getContentLength();
//			post.setEntity(entity);
//			post.addHeader("Accept", "application/xml");
//			// post.addHeader("Content-Type", "application/xml");
//			post.addHeader("Host", "geo.covexis.com");
//			post.addHeader("Accept-Language", "en-us,en;q=0.5");
//			post.addHeader("Accept-Charset", "utf-8");
//			post.addHeader("Content-Type", "text/xml; charset=UTF-8");
//			post.addHeader("Referer", "http://geo.covexis.com/map/");
//			response = client.execute(post);
//			
//			/* Checking response */
//			if (response != null) {
//				// do something...
//				Log.i(tag, "response="+response.toString()); // null
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		return response;
//	}
	
//	public static HttpResponse callWSPost(String url, String body) {
//		HttpResponse response = null;
//		try {
//			HttpPost post = new HttpPost(url);
//			StringEntity entity = new StringEntity(body, "UTF-8");
//			entity.getContentLength();
//			post.setEntity(entity);
//			post.addHeader("Accept", "application/xml");
//			// post.addHeader("Content-Type", "application/xml");
//			post.addHeader("Host", "geo.covexis.com");
//			post.addHeader("Accept-Language", "en-us,en;q=0.5");
//			post.addHeader("Accept-Charset", "utf-8");
//			post.addHeader("Content-Type", "text/xml; charset=UTF-8");
//			post.addHeader("Referer", "http://geo.covexis.com/map/");
//			response = client.execute(post);
//			
//			/* Checking response */
//			if (response != null) {
//				// do something...
//				Log.i(tag, "response="+response.toString()); // null
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		return response;
//	}
	
	public static String callWS(String url) {	
		HttpClient client = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(url);
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);			
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		
		String responseBody = null;
		try {
			responseBody = client.execute(getMethod, responseHandler);
			 Log.i(tag, responseBody);	
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseBody;
	}
	
	// TODO test data get from assets instead of get from server
	public static String callTestInsteadWSByAssets(Context context, String uri) {	
		// get input stream			
		String wordList = "";
	    BufferedReader br = null;
	    try {
	        br = new BufferedReader(new InputStreamReader(context.getAssets().open(uri))); // throwing a FileNotFoundException?
	        String word;
	        while((word = br.readLine()) != null) {
	        	//Log.i(tag, word);
	        	wordList += word; //break txt file into different words, add to wordList
	        }
	        Log.i(tag, "json response="+wordList); //print out words in array
	    }
        catch(IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); //stop reading
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
        }
	    
        return wordList;
	}
		
//	@SuppressWarnings("unused")
//	private String stringFromInputStream(InputStream inputStream){
//		StringBuilder contentBuilder = new StringBuilder();
//		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
//		String inputLine = "";
//		try {
//			while ((inputLine = in.readLine()) != null) {
//				contentBuilder.append(inputLine);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		
//		return contentBuilder.toString();
//	}

//	public Boolean login(final String username, final String password) {
//		String url = "http://geo.covexis.com/map/service.php?authenticate";
//		String body = ConvertFromModelToXML.DOMLogin(username, password);
//		Log.v("nmtan", url);
//		try{
//			HttpResponse response = callWS(url, body);
//			String responseText = stringFromInputStream(response.getEntity().getContent());
//			Log.v("nmtan", responseText);
//			if (responseText.indexOf("Succeed") == -1)
//				return false; 
//			return true;
//		} catch(Exception ex){
//			return false;
//		}
//	}

//	public Boolean logout() {
//		String url = "http://geo.covexis.com/map/service.php?logout";
//		HttpResponse result = callWS(url, "");
//		if (!result.getEntity().equals("sussess"))
//			return false;
//		return true;
//	}

//	public String getSession() {
//		String url = "http://geo.covexis.com/map/service.php?session";
//		String body = ConvertFromModelToXML.DOMSession("08:00");
//		HttpResponse result = callWS(url, body);
//		return result.toString();
//	}

//	public ArrayList<Device> getDeviceList() {
//		String url = "http://geo.covexis.com/map/devices.php?list";
//		String body = "<RequestBody/>";
//		ArrayList<Device> listDevices = null;
//		HttpResponse result = callWS(url, body);
//		try {
//			if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//				String responseText = stringFromInputStream(result.getEntity().getContent());
//				//Log.d("nmtan device", contentBuilder.toString());
//				listDevices = Parse
//						.getListDeviceFromXML(responseText);
//			}
//		} catch (Exception ex) {
//			ex.printStackTrace();
//			return listDevices;
//		}
//		return listDevices;
//	}
	
//	public ArrayList<DeviceState> getStateOfDevices(ArrayList<String> listDeviceID){
//		String url = "http://geo.covexis.com/map/deviceStates.php?list";
//		String body=ConvertFromModelToXML.DOMDeviceState(listDeviceID,listDeviceID);
//		Log.v("postXML", body);
//		HttpResponse result = callWS(url, body);
//		ArrayList<DeviceState> listDevicesState = null;
//		try{
//			if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//					
////				InputStream inputStream = result.getEntity().getContent();
////				StringBuilder contentBuilder = new StringBuilder();
////				BufferedReader in = new BufferedReader(new InputStreamReader(
////						inputStream));
////				String inputLine = "";
////				while ((inputLine = in.readLine()) != null) {
////					contentBuilder.append(inputLine);
////				}
////				String responseText = contentBuilder.toString();
//				HttpEntity entity=result.getEntity();
//				String responseText = EntityUtils.toString(entity);
//				listDevicesState = Parse.getListDeviceStateFromXML(responseText);
//				if (listDevicesState != null) {
//					Log.d("nthuyen","list size " + String.valueOf(listDevicesState.size()));
//					for(DeviceState state:listDevicesState) {
//						Log.d("nthuyen","devicestate="+state.getDeviceId());
//					}
//				}
//			}
//		}catch(Exception ex){
//			ex.printStackTrace();
//			return listDevicesState;
//		}
//		return listDevicesState;
//	}
}
